// 计时器功能模块
document.addEventListener('DOMContentLoaded', function() {
    // 初始化计时器
    initTimer();
    // 加载目标
    loadGoals();
    // 加载今日统计
    loadDailyStats();
    // 加载最近活动
    loadRecentActivities();
});

// 计时器状态
const timerState = {
    mode: 'focus', // focus, short-break, long-break
    timeLeft: 25 * 60, // 初始时间（秒）
    totalTime: 25 * 60, // 总时间（秒）
    isRunning: false,
    interval: null,
    focusCount: 0, // 已完成的专注次数
    settings: {
        focusDuration: 25, // 默认值，将从API获取
        shortBreakDuration: 5,
        longBreakDuration: 15,
        longBreakInterval: 4,
        autoStartBreak: true,
        autoStartFocus: false
    },
    currentGoal: null
};

// 初始化计时器
async function initTimer() {
    // 获取设置
    try {
        const settings = await api('/settings');
        timerState.settings = {
            focusDuration: settings.focus_duration,
            shortBreakDuration: settings.short_break_duration,
            longBreakDuration: settings.long_break_duration,
            longBreakInterval: settings.long_break_interval,
            autoStartBreak: settings.auto_start_break,
            autoStartFocus: settings.auto_start_focus
        };
        
        // 更新初始时间
        updateTimerMode('focus');
    } catch (error) {
        console.error('获取设置失败:', error);
    }
    
    // 模式切换按钮
    const modeButtons = document.querySelectorAll('.mode-btn');
    modeButtons.forEach(button => {
        button.addEventListener('click', function() {
            const mode = this.getAttribute('data-mode');
            updateTimerMode(mode);
        });
    });
    
    // 控制按钮
    const startBtn = document.getElementById('start-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const resetBtn = document.getElementById('reset-btn');
    
    startBtn.addEventListener('click', startTimer);
    pauseBtn.addEventListener('click', pauseTimer);
    resetBtn.addEventListener('click', resetTimer);
    
    // 目标选择
    const goalSelect = document.getElementById('goal-select');
    goalSelect.addEventListener('change', function() {
        const goalId = this.value;
        if (goalId) {
            setCurrentGoal(parseInt(goalId));
        } else {
            timerState.currentGoal = null;
            updateGoalInfo(null);
        }
    });
    
    // 更新界面
    updateTimerDisplay();
}

// 更新计时器模式
function updateTimerMode(mode) {
    // 清除当前定时器
    if (timerState.interval) {
        clearInterval(timerState.interval);
        timerState.interval = null;
        timerState.isRunning = false;
    }
    
    // 保存之前的模式
    const previousMode = timerState.mode;
    
    // 更新模式
    timerState.mode = mode;
    
    // 更新按钮状态
    const modeButtons = document.querySelectorAll('.mode-btn');
    modeButtons.forEach(button => {
        button.classList.toggle('active', button.getAttribute('data-mode') === mode);
    });
    
    // 更新时间
    switch (mode) {
        case 'focus':
            // 如果从休息模式切换回专注模式且已选择目标，使用目标剩余时间和设置时间的较小值
            if ((previousMode === 'short-break' || previousMode === 'long-break') && timerState.currentGoal) {
                const remainingMinutes = timerState.currentGoal.target_time - timerState.currentGoal.completed_time;
                if (remainingMinutes > 0) {
                    const focusDuration = Math.min(remainingMinutes, timerState.settings.focusDuration);
                    timerState.totalTime = focusDuration * 60;
                } else {
                    timerState.totalTime = timerState.settings.focusDuration * 60;
                }
            } else {
                timerState.totalTime = timerState.settings.focusDuration * 60;
            }
            break;
        case 'short-break':
            timerState.totalTime = timerState.settings.shortBreakDuration * 60;
            break;
        case 'long-break':
            timerState.totalTime = timerState.settings.longBreakDuration * 60;
            break;
    }
    
    timerState.timeLeft = timerState.totalTime;
    
    // 更新进度条颜色
    updateTimerColor();
    
    // 更新显示
    updateTimerDisplay();
    updateControlButtons();
}

// 更新计时器颜色
function updateTimerColor() {
    const timerProgress = document.querySelector('.timer-progress');
    
    switch (timerState.mode) {
        case 'focus':
            timerProgress.style.stroke = 'var(--focus-color)';
            break;
        case 'short-break':
            timerProgress.style.stroke = 'var(--short-break-color)';
            break;
        case 'long-break':
            timerProgress.style.stroke = 'var(--long-break-color)';
            break;
    }
}

// 更新计时器显示
function updateTimerDisplay() {
    // 更新时间文本
    const timerTimeElement = document.querySelector('.timer-time');
    timerTimeElement.textContent = formatTime(timerState.timeLeft);
    
    // 更新圆形进度条
    const timerProgress = document.querySelector('.timer-progress');
    const circumference = 2 * Math.PI * 45; // 圆周长
    const progressValue = timerState.timeLeft / timerState.totalTime;
    const dashoffset = circumference * (1 - progressValue);
    
    timerProgress.style.strokeDasharray = circumference;
    timerProgress.style.strokeDashoffset = dashoffset;
    
    // 更新页面标题
    document.title = `${formatTime(timerState.timeLeft)} - ${timerState.mode === 'focus' ? '专注' : '休息'} | 专注时钟`;
}

// 更新控制按钮状态
function updateControlButtons() {
    const startBtn = document.getElementById('start-btn');
    const pauseBtn = document.getElementById('pause-btn');
    const resetBtn = document.getElementById('reset-btn');
    
    startBtn.disabled = timerState.isRunning;
    pauseBtn.disabled = !timerState.isRunning;
    resetBtn.disabled = !timerState.isRunning && timerState.timeLeft === timerState.totalTime;
}

// 开始计时器
function startTimer() {
    if (timerState.isRunning) return;
    
    // 检查是否选择了目标（仅专注模式需要）
    if (timerState.mode === 'focus' && !timerState.currentGoal) {
        alert('请先选择一个目标再开始专注！');
        return;
    }
    
    // 如果是专注模式且有选择的目标，使用目标的目标时间
    if (timerState.mode === 'focus' && timerState.currentGoal) {
        // 检查是否有剩余时间需要完成
        const remainingMinutes = timerState.currentGoal.target_time - timerState.currentGoal.completed_time;
        
        if (remainingMinutes <= 0) {
            alert('此目标已完成！请选择另一个目标或创建新目标。');
            return;
        }
        
        // 使用目标的剩余时间或设置的专注时间，取较小值
        const focusDuration = Math.min(remainingMinutes, timerState.settings.focusDuration);
        timerState.totalTime = focusDuration * 60;
        timerState.timeLeft = timerState.totalTime;
        
        // 更新显示
        updateTimerDisplay();
    }
    
    timerState.isRunning = true;
    updateControlButtons();
    
    const startTime = Date.now() - (timerState.totalTime - timerState.timeLeft) * 1000;
    
    timerState.interval = setInterval(() => {
        const elapsed = Math.floor((Date.now() - startTime) / 1000);
        timerState.timeLeft = Math.max(0, timerState.totalTime - elapsed);
        
        updateTimerDisplay();
        
        if (timerState.timeLeft === 0) {
            clearInterval(timerState.interval);
            timerState.interval = null;
            timerState.isRunning = false;
            handleTimerComplete();
        }
    }, 100);
}

// 暂停计时器
function pauseTimer() {
    if (!timerState.isRunning) return;
    
    clearInterval(timerState.interval);
    timerState.interval = null;
    timerState.isRunning = false;
    
    updateControlButtons();
}

// 重置计时器
function resetTimer() {
    pauseTimer();
    timerState.timeLeft = timerState.totalTime;
    updateTimerDisplay();
    updateControlButtons();
}

// 计时器完成处理
async function handleTimerComplete() {
    updateControlButtons();
    
    // 播放提示音
    playNotificationSound();
    
    // 显示通知
    let title, message;
    
    if (timerState.mode === 'focus') {
        title = '专注时间结束！';
        message = '该休息一下了';
        
        // 如果有关联目标，显示进度信息
        if (timerState.currentGoal) {
            const completedMinutes = Math.floor(timerState.totalTime / 60);
            const newCompletedTime = timerState.currentGoal.completed_time + completedMinutes;
            const targetTime = timerState.currentGoal.target_time;
            const remainingTime = Math.max(0, targetTime - newCompletedTime);
            
            if (remainingTime > 0) {
                message += `\n目标"${timerState.currentGoal.name}"还剩${remainingTime}分钟`;
            } else {
                message += `\n恭喜！目标"${timerState.currentGoal.name}"已完成！`;
            }
        }
    } else {
        title = '休息时间结束！';
        message = '准备开始新的专注吧';
    }
    
    showNotification(title, { body: message });
    
    // 保存会话记录
    if (timerState.mode === 'focus') {
        try {
            await saveFocusSession();
            timerState.focusCount++;
            
            // 更新今日统计
            loadDailyStats();
            
            // 更新最近活动
            loadRecentActivities();
            
            // 自动开始休息
            if (timerState.settings.autoStartBreak) {
                const nextMode = (timerState.focusCount % timerState.settings.longBreakInterval === 0) 
                    ? 'long-break' 
                    : 'short-break';
                updateTimerMode(nextMode);
                startTimer();
            }
        } catch (error) {
            console.error('保存专注会话失败:', error);
        }
    } else {
        // 自动开始下一个专注
        if (timerState.settings.autoStartFocus) {
            updateTimerMode('focus');
            startTimer();
        }
    }
}

// 播放提示音
function playNotificationSound() {
    const audio = new Audio('/static/sounds/notification.mp3');
    audio.play().catch(e => console.error('播放提示音失败:', e));
}

// 保存专注会话
async function saveFocusSession() {
    // 只记录总时间（秒），让后端处理所有时间计算
    const session = {
        type: 'focus',
        duration: timerState.totalTime,
        goal_id: timerState.currentGoal ? timerState.currentGoal.id : null,
        completed: true
    };
    
    console.log('发送的会话数据:', session);
    
    try {
        const result = await api('/focus-sessions', 'POST', session);
        console.log('保存会话响应:', result);
        
        // 如果有关联目标，刷新目标信息
        if (timerState.currentGoal) {
            try {
                const goalId = timerState.currentGoal.id;
                const updatedGoal = await api(`/goals/${goalId}`, 'GET');
                
                // 更新前端状态
                timerState.currentGoal = updatedGoal;
                updateGoalInfo(updatedGoal);
                
                // 如果目标已完成，显示祝贺消息
                if (updatedGoal.completed && !timerState.currentGoal.completed) {
                    const notification = new Notification('目标完成!', {
                        body: `恭喜! 您已完成目标: ${updatedGoal.name}`,
                        icon: '/static/favicon.ico'
                    });
                }
            } catch (error) {
                console.error('获取更新后的目标信息失败:', error);
            }
            
            // 如果统计页面是可见的，刷新统计数据
            const statisticsPage = document.getElementById('statistics-page');
            if (statisticsPage && statisticsPage.classList.contains('active') && window.loadData) {
                window.loadData();
            }
        }
        
        return result;
    } catch (error) {
        console.error('保存会话失败:', error);
        throw error;
    }
}

// 加载目标列表
async function loadGoals() {
    try {
        const goals = await api('/goals');
        
        // 筛选未完成的目标
        const activeGoals = goals.filter(goal => !goal.completed);
        
        // 更新目标选择器
        const goalSelect = document.getElementById('goal-select');
        
        // 清空现有选项
        goalSelect.innerHTML = '<option value="">选择目标...</option>';
        
        // 添加目标选项
        activeGoals.forEach(goal => {
            const option = document.createElement('option');
            option.value = goal.id;
            option.textContent = goal.name;
            goalSelect.appendChild(option);
        });
        
        // 自动选择目标
        if (activeGoals.length > 0) {
            // 获取上次使用的目标ID
            const lastGoalId = localStorage.getItem('lastGoalId');
            
            // 如果有上次使用的目标并且它仍在活动目标中，则选择它
            if (lastGoalId && activeGoals.some(goal => goal.id.toString() === lastGoalId)) {
                goalSelect.value = lastGoalId;
                setCurrentGoal(parseInt(lastGoalId));
            } 
            // 否则选择第一个可用目标
            else {
                goalSelect.value = activeGoals[0].id;
                setCurrentGoal(activeGoals[0].id);
            }
        }
    } catch (error) {
        console.error('加载目标失败:', error);
    }
}

// 设置当前目标
async function setCurrentGoal(goalId) {
    try {
        const goal = await api(`/goals/${goalId}`);
        timerState.currentGoal = goal;
        updateGoalInfo(goal);
        
        // 保存当前选择的目标ID到本地存储
        localStorage.setItem('lastGoalId', goalId.toString());
    } catch (error) {
        console.error('获取目标详情失败:', error);
    }
}

// 更新目标信息显示
function updateGoalInfo(goal) {
    const progressFill = document.querySelector('.progress-fill');
    const progressText = document.querySelector('.progress-text');
    const timeCompleted = document.querySelector('.time-completed');
    const timeTarget = document.querySelector('.time-target');
    
    if (goal) {
        // 确保所有数值都是数字类型
        const completedTime = parseInt(goal.completed_time) || 0;
        const targetTime = parseInt(goal.target_time) || 1; // 防止除以零
        
        // 计算进度百分比，最大为100%
        const progress = Math.min(100, (completedTime / targetTime * 100));
        
        progressFill.style.width = `${progress}%`;
        progressText.textContent = `${Math.round(progress)}%`;
        
        // 显示完成时间和目标时间
        timeCompleted.textContent = completedTime;
        timeTarget.textContent = targetTime;
        
        // 记录日志，帮助调试
        console.log(`目标信息更新: 已完成=${completedTime}分钟, 目标=${targetTime}分钟, 进度=${progress.toFixed(1)}%`);
        
        // 如果目标已完成，添加视觉指示
        if (goal.completed) {
            progressFill.classList.add('completed');
            progressText.classList.add('completed');
        } else {
            progressFill.classList.remove('completed');
            progressText.classList.remove('completed');
        }
    } else {
        progressFill.style.width = '0%';
        progressText.textContent = '0%';
        timeCompleted.textContent = '0';
        timeTarget.textContent = '0';
        
        progressFill.classList.remove('completed');
        progressText.classList.remove('completed');
    }
}

// 加载今日统计
async function loadDailyStats() {
    try {
        // 使用正确年份的当前日期
        const currentDate = getCurrentDate();
        const today = currentDate.toISOString().split('T')[0];
        
        // 记录当前请求的日期，用于调试
        console.log('请求统计数据的日期:', today);
        console.log('使用的年份:', currentDate.getFullYear());
        
        const stats = await api(`/statistics/daily?date=${today}`);
        
        // 更新统计显示
        document.getElementById('focus-count').textContent = stats.focus_count || 0;
        document.getElementById('focus-time').textContent = stats.focus_time || 0;
        document.getElementById('completed-goals').textContent = stats.completed_goals || 0;
        
    } catch (error) {
        console.error('加载今日统计失败:', error);
    }
}

// 加载最近活动
async function loadRecentActivities() {
    try {
        const sessions = await api('/focus-sessions');
        
        // 只显示最近10条记录
        const recentSessions = sessions.slice(0, 10);
        
        const activityList = document.getElementById('activity-list');
        activityList.innerHTML = '';
        
        if (recentSessions.length === 0) {
            const emptyItem = document.createElement('li');
            emptyItem.textContent = '暂无活动记录';
            activityList.appendChild(emptyItem);
            return;
        }
        
        // 获取当前真实年份和时区信息
        const now = getCurrentDate();
        const currentYear = now.getFullYear();
        const timezoneOffset = now.getTimezoneOffset();
        
        console.log('加载活动 - 当前年份:', currentYear);
        console.log('加载活动 - 时区偏移(分钟):', timezoneOffset);
        
        recentSessions.forEach(session => {
            // 解析时间并处理可能的时区问题
            console.log('原始会话数据:', session);
            
            const item = document.createElement('li');
            
            const info = document.createElement('div');
            info.className = 'activity-info';
            
            const title = document.createElement('div');
            title.className = 'activity-title';
            title.textContent = session.type === 'focus' ? '专注' : '休息';
            if (session.goal_name) {
                title.textContent += ` - ${session.goal_name}`;
            }
            
            // 处理日期时间显示
            let startTime;
            try {
                // 解析会话时间并修正年份
                startTime = correctDateYear(new Date(session.start_time));
                console.log('解析后会话开始时间:', startTime.toLocaleString());
            } catch (e) {
                console.error('解析时间出错:', e);
                startTime = getCurrentDate(); // 解析失败时使用当前修正时间
            }
            
            const meta = document.createElement('div');
            meta.className = 'activity-meta';
            
            // 格式化显示日期和时间
            try {
                meta.textContent = startTime.toLocaleString('zh-CN', {
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                });
            } catch (e) {
                console.error('格式化时间出错:', e);
                meta.textContent = '时间未知';
            }
            
            info.appendChild(title);
            info.appendChild(meta);
            
            const time = document.createElement('div');
            time.className = 'activity-time';
            time.textContent = `${Math.floor(session.duration / 60)} 分钟`;
            
            item.appendChild(info);
            item.appendChild(time);
            
            activityList.appendChild(item);
        });
        
    } catch (error) {
        console.error('加载最近活动失败:', error);
    }
} 